﻿using Loamen.KeyMouseHook;
using Loamen.KeyMouseHook.Native;

using SuperSocket.WebSocket;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using MyDxgiScreenCapture;
using System.Runtime.InteropServices;

namespace DeskTopServer
{
    public partial class Form1 : Form
    {
        WebSocketServer ws = new WebSocketServer();
        Dictionary<WebSocketSession, string> userlist = new Dictionary<WebSocketSession, string>();
        InputSimulator sim = new InputSimulator();
        readonly ScreenCapture _screenCapture;
        public Form1()
        {
            int iActulaWidth = Screen.PrimaryScreen.Bounds.Width;
            int iActulaHeight = Screen.PrimaryScreen.Bounds.Height;
            _screenCapture = new ScreenCapture(new Control(), new Rectangle(0, 0, iActulaWidth, iActulaHeight));
            InitializeComponent();
            ws.NewMessageReceived += Ws_NewMessageReceived;//当有信息传入时
            ws.NewSessionConnected += Ws_NewSessionConnected;//当有用户连入时
            ws.NewDataReceived += Ws_NewDataReceived;//当有数据传入时
            ws.SessionClosed += Ws_SessionClosed;//当有用户退出时
            ws.Setup(10086);
            ws.Start();
        }
        //当有用户退出时
        private void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            //throw new NotImplementedException();
            Console.WriteLine("用户退出");
        }
        //当有数据传入时
        private void Ws_NewDataReceived(WebSocketSession session, byte[] value)
        {
            //throw new NotImplementedException();
            Console.WriteLine("当有字节数据传入时");
         
        }

        //当有用户连入时
        private void Ws_NewSessionConnected(WebSocketSession session)
        {
            //throw new NotImplementedException();
            Console.WriteLine("当有用户连入时");
            userlist.Add(session, "");
           SendImage();
        }
        //当有信息传入时
        private void Ws_NewMessageReceived(WebSocketSession session, string value)
        {
 
          //  textBox1.AppendText(value+"\r\n");      
       
            Console.WriteLine("客户端来的命令：" + value);
            var cmd = Newtonsoft.Json.JsonConvert.DeserializeObject<ClientCmd>(value);
            if (cmd.action == "mousemove")
            {              
                var point = new Point(cmd.x, cmd.y).ToAbsolutePoint();
                sim.Mouse.MoveMouseTo(point.X, point.Y);
            }
            else if (cmd.action == "mousedown")
            {
                sim.Mouse.LeftButtonDown();
            }
            else if (cmd.action == "mouseup")
            {
                sim.Mouse.LeftButtonUp();
            }
            else if (cmd.action == "click")
            {
                sim.Mouse.LeftButtonClick();
            }
            else if (cmd.action == "dbclick")
            {
                sim.Mouse.LeftButtonDoubleClick();
            }
            else if (cmd.action == "rightclick")
            {
                sim.Mouse.RightButtonClick();
            }
            else if (cmd.action == "keypress")
            {
                //sim.Keyboard.KeyPress();
            }
            else if (cmd.action=="keyup")
            {
                
                List<VirtualKeyCode> modifiedkey = new List<VirtualKeyCode>();
                if (cmd.shift)
                {
                    modifiedkey.Add(VirtualKeyCode.SHIFT);
                }
                if (cmd.ctrl)
                {
                    modifiedkey.Add(VirtualKeyCode.CONTROL);
                }
                if (cmd.alt)
                {
                    modifiedkey.Add(VirtualKeyCode.MENU);
                }
               
                sim.Keyboard.ModifiedKeyStroke(modifiedkey, (VirtualKeyCode)cmd.key);
            }
            //接到操作的时候发送数据
           // SendImage();
        }

        private void SendImage() {
            while (true) {
                //Thread.Sleep(10);

                //var bitmap= ScreenCapture.Capture();
                //var imgbyte = ScreenCapture.Bitmap2Byte(bitmap);
                //for (int i = 0; i < userlist.Count; i++)
                //{                       
                //    userlist.ElementAt(i).Key.Send(imgbyte, 0, imgbyte.Length);
                //}          
                Thread.Sleep(40);
                var e = _screenCapture.CaptureImage();
                if (e==null)
                {
                    continue;
                }                
              
                byte[] imgbyte = e.GetAsByte(); 
               
                for (int i = 0; i < userlist.Count; i++)
                {
                    userlist.ElementAt(i).Key.Send(imgbyte, 0, imgbyte.Length);
                }
            }

        }

        private void button1_Click(object sender, EventArgs ev)
        {
            var e = _screenCapture.CaptureImage();
            IntPtr srcPtr = e.Data.DataPointer;

           
            for (int i = 0; i < e.Data.Length; i += 4)
            {
                byte b = Marshal.ReadByte(srcPtr);
                byte g = Marshal.ReadByte(srcPtr + 1);
                byte r = Marshal.ReadByte(srcPtr + 2);
            }

          
            System.Drawing.Bitmap bitmap = e.GetAsBitmap();
            // bitmap.Save("F:\\test.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
            // _screenCapture.CloseManager();//释放资源
        }
    }
}
